package xdsysadmin2

import grails.transaction.Transactional
import initConfig.SysInitData
import model.EleTree
import model.SelectData
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import org.jsoup.select.Elements
import sysAuth.SysDepartments
import sysAuth.SysFunctions
import sysAuth.SysOperations
import sysAuth.SysOrganization
import sysAuth.SysRoleRela
import sysAuth.SysRoleRelaOperat
import sysAuth.SysRoles
import sysAuth.SysUserRoles
import sysAuth.SysUsers
import sysUtil.PageUtil
import sysUtil.ResultCode
import sysUtil.SysAuthSQL
import sysUtil.SysCommUtil
import xdTool.XdWidgetDate
import xdTool.XdWidgetInput
import xdTool.XdWidgetPanel
import xdTool.XdWidgetPanelParam
import xdTool.XdWidgetReport
import xdTool.XdWidgetReportPanel
import xdTool.XdWidgetReportPanelAct
import xdTool.XdWidgetReportParam
import xdTool.XdWidgetReportParamAct
import xdTool.XdWidgetSelect

@Transactional
class AuthUtilsService {

    /**
     * 根据用户ID，获取数据权限和功能权限
     * @param userNo
     * @param roleType:"FUNC_ROLE":"功能角色","DATA_ROLE":"数据角色"
     */

    def sysDBUtilService

    def  listRolesByUserAndRoleType(SysUsers user,String roleType){
        def relations = SysUserRoles.findAllByUser(user)
        def c = SysRoles.createCriteria()
        def result = c.list{
            eq("roleType",roleType)
            or {
                inList("id",relations.role.id?:[null])
                eq("creator",user.userNo )
            }
        }
        return result
    }

    /**
     * 用户级别：0:超级管理员角色，1：菜单管理员角色,2:数据管理员角色，3：普通用户,4：非法用户
     * @param user
     * @return
     */
    def isAvailable(SysUsers userInstance){
        if(userInstance){
            def relations = SysUserRoles.findAllByUser(userInstance)
            if(relations){
                def roles = SysRoles.findAllByIdInList(relations.role.id)
                if(roles){
                    if(roles.roleNo.contains(SysInitData.ADMIN_DATA_ROLE ) && roles.roleNo.contains(SysInitData.ADMIN_FUNC_ROLE )){
                        return 0
                    }else if(roles.roleNo.contains(SysInitData.ADMIN_FUNC_ROLE )){
                        return 1
                    }else if(roles.roleNo.contains(SysInitData.ADMIN_DATA_ROLE )){
                        return 2
                    }else{
                        return 3
                    }
                }else {
                    return 4
                }
            }else {
                return 4
            }
        }else{
            return 4;
        }
    }
    /**
     * 获取完整菜单树
     * @return
     */
    def listAdminTreeFuncByParent(){
        def parentFunction =   SysFunctions.findAllByParentIdIsNull([sort: "orderNum"])
        def childrenFunction = SysFunctions.findAllByParentIdIsNotNull([sort: "orderNum"])
        return SysCommUtil.listFindTree(parentFunction,childrenFunction,"id","parentId","children" )
    }

    /**
     * 获取完整菜单树
     * @return
     */
    def listUserTreeFuncByParent(SysUsers user){
        def parentFunction =   listParentFuncByUserAuth(user)
//        println parentFunction
        def childrenFunction = listChildrenFuncByUserAuth(user)

        return SysCommUtil.listFindTree(parentFunction,childrenFunction,"id","parentId","children" )
    }

    /**
     * 根据用户权父节点菜单
     * @param user
     * @return
     */
    def   listParentFuncByUserAuth(SysUsers user){
        def FUNC_ROLE = SysInitData.FUNC_ROLE

        def data = listDataByUserAndRoleType(user,FUNC_ROLE)
        //println data
        def c = SysFunctions.createCriteria()
        def result = c.list {
            isNull("parentId")
            eq("state","1")
            if(!SysInitData.USER_GRADE_ADMIN_FUNC.contains(isAvailable(user))){
                or{
                    eq("creator",user.userNo )
                    inList("id",data.dataId?:[null])
                }
            }
            order("orderNum","asc")
        };

        return result
    }

    /**
     * list user children menu
     * @param user
     * @return
     */
    def   listChildrenFuncByUserAuth(SysUsers user){
        def FUNC_ROLE = SysInitData.FUNC_ROLE

        def data = listDataByUserAndRoleType(user,FUNC_ROLE)
        def c = SysFunctions.createCriteria()
        def result = c.list(){
            isNotNull("parentId")
            if(!SysInitData.USER_GRADE_ADMIN_FUNC.contains(isAvailable(user))){
                or{
                    eq("creator",user.userNo)
                    inList("id",data.dataId?:[null])
                }
            }
            eq("state","1")
            order("orderNum","asc")
        }
        return result
    }

    /**
     * 根据用户获取所有菜单
     * @param user
     * @return
     */
    def listFunctionByUserAuth(params){
        //println params
        def FUNC_ROLE = SysInitData.FUNC_ROLE
        def user = SysUsers.findByUserNo(params.userNo)
        def funcName = params?.funcName
        def data = listDataByUserAndRoleType(user,FUNC_ROLE)
        def criteria = SysFunctions.createCriteria()
        def result = criteria.list{

            if(!SysInitData.USER_GRADE_ADMIN_FUNC.contains(isAvailable(user))){
                or{
                    eq("creator",user.userNo)
                    inList("id",data.dataId?:[null])
                }
            }

            if(funcName){
                or {
                    like("funcName","%${funcName}%")
                    like("funcNo","%${funcName}%")
                }
            }
            order("parentId","asc")
            order("orderNum","asc")
        }
        return result
    }

    /**
     * 根据权限get菜单
     * @param user
     * @param userGrade
     * @return
     */
    def getFuncTreeByAuth(SysUsers user, int userGrade){
        if( userGrade <= 1){
            return listAdminTreeFuncByParent()
        }else{
            return listUserTreeFuncByParent(user)
        }
    }


    /**
     * 根据用户权限获取菜单、数据
     * @param user
     * @param roleType
     * @param roles
     * @return
     */
    def  listDataByUserAndRoleType(SysUsers user,String roleType ){
        def userGrade= isAvailable(user)
        def USER_GRADE_ADMIN = SysInitData.USER_GRADE_ADMIN_FUNC
        if(roleType == SysInitData.DATA_ROLE){
            USER_GRADE_ADMIN = SysInitData.USER_GRADE_ADMIN_DATA
        }
        def criteria = SysRoleRela.createCriteria()
        def roleRelaData = criteria.list{
            eq("roleType",roleType)
            if(!USER_GRADE_ADMIN.contains(userGrade)){
                def sysUserRole = SysUserRoles.findAllByUser(user);
                inList("role",sysUserRole.role?:[null])
            }
        }
        return roleRelaData
    }


    /**
     * 获取用户清单
     * @param user
     * @param params
     * @return
     */
    def listUsersByAuth(SysUsers user,params){
        def userGrade = isAvailable(user)
        def c = SysUsers.createCriteria()

        def result = c.list(offset: params.offset?:0,max:params.max?:10) {

            if (!SysInitData.USER_GRADE_ADMIN_DATA.contains(userGrade)) {
                inList("orgId", listDataByUserAndRoleType(user, SysInitData.DATA_ROLE)?.dataId?:[null])
            }
            if (params.searchName) {
                or {
                    like("userName", params.searchName + "%")
                    like("userNo", params.searchName + "%")
                }
            }
            order("dateCreated", "desc")
        }
        return result
    }

    /**
     * 获取菜单已配置对操作
     * @param dataSource
     * @param funcId
     * @return
     */
    def listFuncOperate(funcId){
        def sql = SysAuthSQL.getFuncOperate(funcId)
        def db = sysDBUtilService.getGroovySqlInstance( )
        return db.rows(sql)
    }

    /**
     * 根据用户数据权限获取用户清单
     * @param user
     */
    def getUserListByAuth( params){
        String userNo = params.userNo?:""
        def offset = Integer.parseInt(params.page?:1)
        def max = Integer.parseInt(params.limit?:10)
        def userGrade = this.isAvailable(SysUsers.findByUserNo(userNo))
        def searchStr = params.searchStr?:""
        def deptId =  params.deptId?:""
        def sql = SysAuthSQL.getUserListSQL(userNo,userGrade,searchStr,deptId)
        def list = sysDBUtilService.pageResult(sql,offset,max,sysDBUtilService.getGroovySqlInstance())
        def count = sysDBUtilService.pageCount(sql,sysDBUtilService.getGroovySqlInstance())
        return [list:list,count:count]
    }

    /**
     * 根据用户权限获取单只报表的按钮权限
     * @param params
     */
    def getFuncOptsByAuth(params){
        //def userGrade = isAvailable(SysUsers.findByUserNo(params.userNo))
        //def buttonAuth= getFuncOptListByAuth( params.userNo,  params?.funcId,  userGrade, null)
        def buttonAuth = getFuncOptsByAuthList(params)
        def toolbarDom = PageUtil.toolBarHtml(buttonAuth)
        return toolbarDom
    }

    /**
     * 根据用户权限获取单只报表的按钮权限
     * @param params
     */
    def getFuncOptsByAuthList(params){
        def userGrade = isAvailable(SysUsers.findByUserNo(params.userNo))
        def buttonAuth= getFuncOptListByAuth( params.userNo,  params?.funcId,  userGrade, null)
        return buttonAuth
    }

    /**
     * 获取部门权限
     * @param params
     */
    def selectDeptTreeData(params){
        def root = []
        def children = []
        def userNo = params.userNo
        def userGrade = isAvailable(SysUsers.findByUserNo(userNo))
        def criteria = SysDepartments.createCriteria()
        criteria.list{
            if(!SysInitData.USER_GRADE_ADMIN_DATA.contains(userGrade)){
                or {
                    eq("creator",userNo)
                    and {
                        eq("creator",SysInitData.SYS_ADMIN)
                        isNull("parentId")
                    }
                }
            }
            order("parentId")
            order("orderNum")
        }?.each{
            SelectData selectData = new SelectData(name:it.getName(),value:it.id,parentId:it.parentId,disabled: it.state=="0"?"disabled":"")
            if(it.parentId){
                children.add(selectData)
            }else {
                root.add(selectData)
            }
        }

        return SysCommUtil.listFindTree(root,children,"value","parentId","children" )
    }


    /**
     * 区域树（带用户权限）
     */
    def selectOrgTreeData(params){
        def root = []
        def children = []
        def userNo = params.userNo
        def userGrade = isAvailable(SysUsers.findByUserNo(userNo))
        def keyword = params?.keyword
        def roleRelaData = listDataByUserAndRoleType(SysUsers.findByUserNo(userNo),SysInitData.DATA_ROLE)
        def criteria = SysOrganization.createCriteria()
        def result =  criteria.list {

            if(keyword){
                like("name","%${keyword}%")
            }

            if(!SysInitData.USER_GRADE_ADMIN_DATA.contains(userGrade)){

                or {
                    inList("id",roleRelaData.dataId?:[null])
                    eq("creator",userNo)
                    and {
                        eq("creator",SysInitData.SYS_ADMIN)
                        isNull("parentId")
                    }
                }
            }
            order("parentId")
            order("orderNum")
        }

        result?.each{
            if(it.parentId){
                SelectData selectData = new SelectData(name:it.getName(),value:it.id,parentId:it.getParentId(),disabled: it.state=="0"?"disabled":"")
                children.add(selectData)
            }else {
                SelectData selectData = new SelectData(name:it.getName(),value:it.id,parentId:it.getParentId(),disabled: it.state=="0"?"disabled":"")
                root.add(selectData)
            }
        }
        return SysCommUtil.listFindTree(root,children,"value","parentId","children" )
    }


    /**
     * 区域树（带用户权限 和 角色权限）
     */
    def listOrgTreeData(params){

        def root = []
        def children = []
        def userNo = params.userNo
        def userGrade = isAvailable(SysUsers.findByUserNo(userNo))
        def roleId = params?.roleId
        def datas = []
        def roleRelaData = listDataByUserAndRoleType(SysUsers.findByUserNo(userNo),SysInitData.DATA_ROLE)
        if(roleId){
            def role  = SysRoles.get(Long.parseLong(roleId))
            datas = SysRoleRela.findAllByRole(role).dataId
        }

        def criteria = SysOrganization.createCriteria()

        def result = criteria.list {
            //eq("state","1")
            if(!SysInitData.USER_GRADE_ADMIN_DATA.contains(userGrade)){
                or {
                    inList("id",roleRelaData.dataId?:[null])
                    eq("creator",userNo)
                }
            }
            order("parentId")
            order("orderNum")
        }

        result?.each{
            EleTree eleTree = new EleTree(name:it.getName(),label:it.getName(),orgNo: it.orgNo,id:it.id,
                    parentId: it.parentId,orderNum: it.orderNum,marks: it.marks,state:it.state,
                    disabled: it.state=="1"?false:true,checked:datas.contains(it.id) )

            if(it.parentId){
                children.add(eleTree)
            }else {
                root.add(eleTree)
            }
        }
        return SysCommUtil.listFindTree(root,children,"id","parentId","children" )
    }

    /**
     * 部门（带用户权限）
     */


    def listDeptTreeData(params){

        def root = []
        def children = []
        def userNo = params.userNo
        def userGrade = isAvailable(SysUsers.findByUserNo(userNo))

        def sql = SysAuthSQL.getDeptSql(userNo,userGrade)
        def deptList = sysDBUtilService.pageAllResult(sql,sysDBUtilService.getGroovySqlInstance())

        deptList.each{
            EleTree eleTree = new EleTree(name:it.NAME,label:it.NAME,deptNo: it.DEPT_NO,
                    id:it.ID,parentId: it.PARENT_ID,orderNum: it.ORDER_NUM,marks: it.MARKS,state: it.STATE )

            if(eleTree.parentId){
                children.add(eleTree)
            }else {
                root.add(eleTree)
            }
        }
        return SysCommUtil.listFindTree(root,children,"id","parentId","children" )
    }


    /**
     *获取角色清单
     * @param params
     */
    def listRoleListData(params){
        def userNo = params?.userNo
        def userGrade = isAvailable(SysUsers.findByUserNo(userNo))
        def roleType = params.roleType?:SysInitData.FUNC_ROLE
        def authUserId = params?.authUserId
        def result = sysDBUtilService.getGroovySqlInstance().rows(SysAuthSQL.getRoleListSQL(userNo,roleType,userGrade,authUserId))
        return result
    }

    /**
     *更新角色-区域
     * @param params
     */
    def updateRoleData(params){
        def role = SysRoles.get(Long.parseLong(params?.roleId))
        if(role.roleType == SysInitData.FUNC_ROLE){
            //println "config role-function....."
            return updateRoleFunction(params)
        }
        //println "config role-data....."
        def userNo = params?.userNo
        def user = SysUsers.findByUserNo(userNo)
        def userGrade = isAvailable(user)
        def org = SysOrganization.get(Long.parseLong(params?.dataId))
        def count = 0
        def checked = Boolean.parseBoolean(params.checked)
        //println SysCommUtil.domainToMap(role)
        if (checked){
            //插入上级节点
            def result = SysCommUtil.listParentByChild(org,"parentId")
            result.each {
                def sysRoleRela = SysRoleRela.findByRoleAndDataIdAndRoleType(role,it.id,SysInitData.DATA_ROLE)

                if(!sysRoleRela  && it.state !="0"){
                    new SysRoleRela(role: role,roleType: SysInitData.DATA_ROLE,dataId: it.id).save(flush: true)
                    count ++;
                }
            }

            //插入下级节点
            def rangeList =  SysOrganization.findAll {
                if(!SysInitData.USER_GRADE_ADMIN_DATA.contains(userGrade)){
                    def data = listDataByUserAndRoleType(user,SysInitData.DATA_ROLE)
                    inList("id",data.dataId?:[null])
                }
            }
            def rst = SysCommUtil.listChildByParent(org,rangeList,"id","parentId")
            rst.each {
                def instance = SysRoleRela.find("from SysRoleRela as a where a.roleType='${SysInitData.DATA_ROLE}' and a.dataId=${it.id} and a.role.id=${role.id}")
                if(!instance && it.state !="0"){
                    new SysRoleRela(role: role,roleType: SysInitData.DATA_ROLE,dataId: it.id).save(flush: true)
                    count ++;
                }
            }

        }else {
            def rangeList =  SysOrganization.findAll {
                inList("id",SysRoleRela.findAllByRole(role).dataId?:[null])
            }
            def rst = SysCommUtil.listChildByParent(org,rangeList,"id","parentId")

            rst.each {
                def instance = SysRoleRela.find("from SysRoleRela as a where a.roleType='${SysInitData.DATA_ROLE}' and a.dataId=${it.id} and a.role.id=${role.id}")
                if(instance){
                    instance.delete(flush: true)
                }
                count ++;
            }
        }
        return count
    }

    /**
     * 获取菜单操作按钮
     * @param userNo
     * @param funcId
     * @param userGrade
     * @return
     */
    def getFuncOptListByAuth(userNo,funcId,userGrade,roleId){
        def sql = SysAuthSQL.getFuncOptsByAuth(userNo,funcId,userGrade,roleId)
        return sysDBUtilService.pageAllResult(sql,sysDBUtilService.getGroovySqlInstance()).unique()
    }
    def getFuncOptListByRole(roleId){
        def sql = SysAuthSQL.getFuncOptsByRole(roleId)
        return sysDBUtilService.pageAllResult(sql,sysDBUtilService.getGroovySqlInstance()).unique()
    }


    /**
     * 功能菜单数 - 带操作权限：角色-菜单 分配使用
     * @param params
     */
    def listFunctionTreeData(params){
        def root = []
        def children = []
        def userNo = params.userNo
        def user = SysUsers.findByUserNo(userNo)
        def userGrade = isAvailable(user)
        def roleId = params?.roleId
        def role
        if(roleId){
            role  = SysRoles.get(Long.parseLong(roleId))
        }

        def roleRelaData =  listDataByUserAndRoleType(user,SysInitData.FUNC_ROLE)
        //println userGrade
        def result =  SysFunctions.findAll {
            if(!SysInitData.USER_GRADE_ADMIN_FUNC.contains(userGrade)){
                or {
                    inList("id",roleRelaData.dataId?:[null])
                    eq("creator",userNo)
                }
            }
            eq("state","1")
            order("parentId")
            order("orderNum")
        }
        //println result

        def datas = SysRoleRela.findAllByRole(role)?.dataId
        result.each{
            EleTree eleTree = new EleTree(name:it.funcName,
                    label:"<i class='layui-icon ${it.icon?:"layui-icon-tips"}' ></i>&nbsp;${it.funcName}",
                    orgNo: it.funcNo,id:it.id,
                    parentId: it.parentId,orderNum: it.orderNum,marks: it.marks,
                    disabled: it.state=="1"?false:true,checked:datas.contains(it.id) )

            if(it.parentId){
                children.add(eleTree)

            }else {
                root.add(eleTree)
            }
        }

        //获取每个菜单的操作按钮
        def funcOptList = getFuncOptListByAuth(userNo,null,userGrade,null)
        def hasOptlist =  getFuncOptListByRole(roleId)
        //设置按钮选中状态
        funcOptList.each{
            EleTree eleTree = new EleTree(name:it.OPERATE_NAME,
                    label: "<i class='layui-icon ${it.ICON?:"layui-icon-tips"}' style='color: red;'></i>&nbsp;${it.OPERATE_NAME}",
                    codeNo: it.OPERATE_NO,id:"${it.FUNCTION_ID}_${it.ID}",
                    parentId: it.FUNCTION_ID, isLeaf: true, checked:hasOptlist?.contains(it)
            )
            children.add(eleTree)
        }

        //置按钮父节点ID为 菜单ID
        return SysCommUtil.listFindTree(root,children,"id","parentId","children" )
    }

    /**
     * 更新角色-菜单 && 角色-菜单-操作按钮
     * @param params
     */
    def updateRoleFunction(params){
        //println params
        def role = SysRoles.get(Long.parseLong(params?.roleId))
        def userNo = params?.userNo
        def user = SysUsers.findByUserNo(userNo)
        def userGrade = isAvailable(user)
        def count = 0
        def checked = Boolean.parseBoolean(params.checked)
        def dataId = String.valueOf(params?.dataId)
        def relaOptId
        if(dataId && dataId.indexOf("_")!=-1){
            relaOptId = dataId.split("_")[1]
            dataId = dataId.split("_")[0]
        }
        def function = SysFunctions.get(Long.parseLong(dataId))
        if(checked){
            //插入上级节点
            def result = SysCommUtil.listParentByChild(function,"parentId")

            result.each {
                def sysRoleRela = SysRoleRela.findByRoleAndDataIdAndRoleType(role,it.id,SysInitData.FUNC_ROLE)
                if(!sysRoleRela && it.state !="0"){
                    new SysRoleRela(role: role,roleType: SysInitData.FUNC_ROLE,dataId: it.id).save(flush: true)
                    count ++;
                }
            }

            //插入当前操作按钮
            if(relaOptId){

                def sysRoleRela = SysRoleRela.findByRoleAndDataIdAndRoleType(role,Long.parseLong(dataId),SysInitData.FUNC_ROLE)
                SysRoleRelaOperat sysRoleRelaOperat = SysRoleRelaOperat.findBySysFunOptIdAndRelaId(Long.parseLong(relaOptId),sysRoleRela.id)

                if(!sysRoleRelaOperat){
                    new SysRoleRelaOperat(relaId:sysRoleRela.id,sysFunOptId: Long.parseLong(relaOptId)).save(flush: true)
                }
            }else{
                //插入下级节点
                //println relaOptId
                def rangeList =  SysFunctions.findAll {
                    if(!SysInitData.USER_GRADE_ADMIN_FUNC.contains(userGrade)){
                        def data = listDataByUserAndRoleType(user,SysInitData.FUNC_ROLE)
                        inList("id",data.dataId?:[null])
                    }
                }

                def rst = SysCommUtil.listChildByParent(function,rangeList,"id","parentId")

                rst.each {
                    def instance = SysRoleRela.findByRoleAndDataIdAndRoleType(role,it.id,SysInitData.FUNC_ROLE)
                    if(!instance  && it.state !="0"){
                        instance = new SysRoleRela(role: role,roleType: SysInitData.FUNC_ROLE,dataId: it.id).save(flush: true)
                        //添加 按钮
                    }

                    def funcOptList = getFuncOptListByAuth(userNo,it.id,userGrade,null)

                    if(funcOptList && instance){
                        funcOptList.each { relaOpt ->
                            SysRoleRelaOperat sysRoleRelaOperat = SysRoleRelaOperat.findBySysFunOptIdAndRelaId(relaOpt.ID,instance.id)
                            if(!sysRoleRelaOperat){
                                new SysRoleRelaOperat(relaId:instance.id,sysFunOptId: relaOpt.ID).save(flush: true)
                            }
                        }
                    }
                    count ++;
                }
            }
        }else{

            if(relaOptId){
                def sysRoleRela = SysRoleRela.findByRoleAndDataIdAndRoleType(role,Long.parseLong(dataId),SysInitData.FUNC_ROLE)
                SysRoleRelaOperat sysRoleRelaOperat = SysRoleRelaOperat.findBySysFunOptIdAndRelaId(Long.parseLong(relaOptId),sysRoleRela?.id)
                if(sysRoleRelaOperat){
                    sysRoleRelaOperat.delete(flush: true)
                    count ++;
                }
            }else {
                def rangeList =  SysFunctions.findAllByIdInList(SysRoleRela.findAllByRole(role).dataId)
                def rst = SysCommUtil.listChildByParent(function,rangeList,"id","parentId")
                rst.each {
                    def instance = SysRoleRela.findByRoleAndDataIdAndRoleType(role,it.id,SysInitData.FUNC_ROLE);
                    if(instance){
                        SysRoleRelaOperat.findAllByRelaId(instance.id).each {
                            it.delete(flush: true)
                        }
                        instance.delete(flush: true)
                    }
                    count ++;
                }
            }
        }
        return count
    }

    /**
     * 用户新增-角色
     * @param params
     */
    def addSysUserRole(params){
        def checked = Boolean.parseBoolean(params.checked)
        def role = SysRoles.get(params.roleId)
        def user = SysUsers.get(params.userId)
        def userGrade = isAvailable(user)
        if( user.userNo == SysInitData.SYS_ADMIN ){
            //如果正在修改系统管理员权限，则返回错误code
            return ResultCode.OPT_SYS_AUTH
        }
        SysUserRoles sysUserRoles = SysUserRoles.findByRoleAndUser(role,user)
        if(checked){
            if(!sysUserRoles){
                new SysUserRoles(role: role,user: user).save(flush: true)
            }
        }else{
            if(sysUserRoles){
                sysUserRoles.delete(flush: true)
            }
        }
        return ResultCode.TABLE_DATA_SUCCESS
    }

    /**
     * 获取操作按钮清单
     * @param params
     * @return
     */
    def listOptionData(params){
        def sql = SysAuthSQL.getFuncOperate(null)
        return sysDBUtilService.pageAllResult(sql,sysDBUtilService.getGroovySqlInstance())
    }

    /**
     * 更新操作按钮
     * @param params
     * @return
     */
    def updateOption(params){
        def id = Long.parseLong(params.id)
        def field = SysCommUtil.underlineToCamel(params.field)
        def value = String.valueOf(params.value).trim()
        def option = SysOperations.get(id)

        if(field == "operateNo"){
            def oldOpt = SysOperations.findByOperateNo(value)
            if(oldOpt && option.id != oldOpt.id){
                return  ResultCode.EXISTS_ERROR
            }
        }else if(field == "orderNum"){
            value = Integer.parseInt(value)
        }
        option.setProperty(field,value)
        option.save(flush: true)
        return ResultCode.TABLE_DATA_SUCCESS
    }

    /**
     * 新增按钮
     * @param params
     * @return
     */
    def addOption(params){

        def operateNo = String.valueOf(params.operateNo).trim()
        def oldOpt = SysOperations.findByOperateNo(operateNo)
        if(oldOpt){
            return  ResultCode.EXISTS_ERROR
        }else{
            new SysOperations(operateNo: operateNo,operateName: operateNo,creator: params.userNo).save(flush: true)
        }
        return ResultCode.TABLE_DATA_SUCCESS
    }

    /**
     * 获取params list
     * @param params
     */
    def getParams(params){
        def paramsType = params?.paramsType
        def keyword = params?.keyword
        def offset = Integer.parseInt(String.valueOf(params.page?:"1"))
        def max = Integer.parseInt(String.valueOf(params.limit?:"10"))
        def state = params.state?:"1"
        def sql = SysAuthSQL.getParams(paramsType,keyword,state)
        def list =  sysDBUtilService.pageResult(sql,offset,max,sysDBUtilService.getGroovySqlInstance())
//        def count = sysDBUtilService.pageCount(sql,sysDBUtilService.getGroovySqlInstance())

        return  list
    }

    /**
     * 获取首页 未读消息数量
     */
    def getIndexNoticeCountByType(params){
        def userNo = params?.userNo
        def type = params?.type
        def userGrade = isAvailable(SysUsers.findByUserNo(userNo))
        def sql = SysAuthSQL.getIndexNoticeCountByType(userNo, type,userGrade)
        //println sql
        def rst1 = sysDBUtilService.pageCount(sql,sysDBUtilService.getGroovySqlInstance())
        return rst1
    }

    /**
     * 根据ID获取all notice
     * @param id
     * @return
     */
    def getAllNoticeById(id,toUser){
        def sql = SysAuthSQL.getAllNoticeByIdSql(id,toUser)
        def rst1 = sysDBUtilService.pageAllResult(sql,sysDBUtilService.getGroovySqlInstance())
        return rst1
    }
    /**
     * user 动态查询 select
     * @param params
     */
    def getUserSelectList(params){
        def userNo = params.userNo
        def userGrade = isAvailable(SysUsers.findByUserNo(userNo))
        def searchStr = params.keyword?:params?.searchStr
        def deptId  = params?.deptId
        def sql = SysAuthSQL.getUserListSQL(userNo,userGrade,searchStr,deptId)

        def list = sysDBUtilService.pageResult(sql,1,10,sysDBUtilService.getGroovySqlInstance())
        def result = []
        list.each {
            def aa = [name:"${it.USER_NAME} ${it.DEPT_NAME}" ,value: it.USER_NO ]
            result.add(aa)
        }
        return result
    }


    /**
     * 根据rptId 获取form列表
     * @param rptId
     * @return
     */
    def getRptParamListById(rptId){
        def result = []
        List<XdWidgetReportParam> xdWidgetPanelParam = XdWidgetReportParam.findAll("from XdWidgetReportParam as a where a.rptId = ${rptId} order by a.orderNum")
        xdWidgetPanelParam?.each {
            def classFlag = it.classFlag
            switch (it.classFlag){
                case "xd-input":
                    def map = SysCommUtil.copyMap(XdWidgetInput.get(it.paramId))
                    map.put("classFlag",classFlag)
                    result.add(map)
                    break;
                case "xd-select":
                    def map = SysCommUtil.copyMap(XdWidgetSelect.get(it.paramId))
                    map.put("classFlag",classFlag)
                    result.add(map)
                    break;
                case "xd-date":
                    def map = SysCommUtil.copyMap(XdWidgetDate.get(it.paramId))
                    map.put("classFlag",classFlag)
                    result.add(map)
                    break;
            }
        }
        return result
    }

    /**
     * 根据rptId 获取form列表
     * @param rptId
     * @return
     */
    def getRptParamListActById(rptId){
        def result = []
        List<XdWidgetReportParamAct> xdWidgetPanelParam = XdWidgetReportParamAct.findAll("from XdWidgetReportParamAct as a where a.rptId = ${rptId} order by a.orderNum")
        xdWidgetPanelParam?.each {
            def classFlag = it.classFlag
            switch (it.classFlag){
                case "xd-input":
                    def map = SysCommUtil.copyMap(XdWidgetInput.get(it.paramId))
                    map.put("classFlag",classFlag)
                    result.add(map)
                    break;
                case "xd-select":
                    def map = SysCommUtil.copyMap(XdWidgetSelect.get(it.paramId))
                    map.put("classFlag",classFlag)
                    result.add(map)
                    break;
                case "xd-date":
                    def map = SysCommUtil.copyMap(XdWidgetDate.get(it.paramId))
                    map.put("classFlag",classFlag)
                    result.add(map)
                    break;
            }
        }
        return result
    }


    /**
     * 针对新增和删除rpt关联的panel重新排序
     * @param rptId
     */
    def updateRptPanelOrder(rptId){
        def data = XdWidgetReportPanel.findAll("from XdWidgetReportPanel as a where a.rptId = :rptId order by a.orderNum",[rptId:rptId])
        data?.eachWithIndex { XdWidgetReportPanel entry, int i ->
            entry.setOrderNum(i)
            entry.save(flush: true)
        }
    }

    /**
     * 针对新增和删除rpt关联的panel重新排序
     * @param rptId
     */
    def updateRptParamOrder(rptId){
        def data = XdWidgetReportParam.findAll("from XdWidgetReportParam as a where a.rptId = :rptId order by a.orderNum",[rptId:rptId])
        data?.eachWithIndex { XdWidgetReportParam entry, int i ->
            entry.setOrderNum(i)
            entry.save(flush: true)
        }
    }

    /**
     * 获取rpt布局html，填充为正式html
     */
    def updateRptViewPanelHtml(XdWidgetReport xdWidgetReport){
        Document doc = Jsoup.parseBodyFragment(SysCommUtil.Clob2String(xdWidgetReport.tempBody));
        Element element =  doc.body()
        //遍历.rpt-light ：rpt-light为每个布局实际放元素的容器
        Elements rptLights = element.select(".rpt-light")
        for (Element elem: rptLights){
            //遍历有id属性的span:id值为panelId
            Elements panelElems = elem.select("span[id]")
            StringBuffer stringBuffer = new StringBuffer("")
            for (Element panelElem:panelElems){
                String panelId = panelElem.id()
                if(panelId){
                    XdWidgetPanel xdWidgetPanel = XdWidgetPanel.get(Long.parseLong(panelId))
                    if(xdWidgetPanel){
                        stringBuffer.append(SysCommUtil.Clob2String(xdWidgetPanel.html))
                    }
                }
            }
            elem.html(stringBuffer.toString())
        }
        xdWidgetReport.setViewBody(SysCommUtil.String2Clob(element.html()))
    }


    /**
     * 获取rpt布局html，填充为正式html
     */
    def updateRptViewParamHtml(XdWidgetReport xdWidgetReport){
        Document doc = Jsoup.parseBodyFragment(SysCommUtil.Clob2String(xdWidgetReport.tempHeader));
        Element element =  doc.body()
        //遍历.rpt-light ：rpt-light为每个布局实际放元素的容器
        Elements rptLights = element.select(".rpt-light")
        for (Element elem: rptLights){
            //遍历有id属性的span:id值为panelId
            Elements panelElems = elem.select("span[param-id]")
            StringBuffer stringBuffer = new StringBuffer("")
            for (Element paramElem:panelElems){
                String paramId = paramElem.attr("param-id")
                String classFlag = paramElem.attr("class-flag")
                //println "paramId:${paramId} classFlag:${classFlag}"
                if(paramId && classFlag){
                    def instance = this.getWidgetParamByClassFlagAndId(classFlag,paramId)
                    if(instance){
                        stringBuffer.append(SysCommUtil.Clob2String(instance.html))
                    }
                }
            }
            //println stringBuffer.toString()
            elem.html(stringBuffer.toString())
        }
        xdWidgetReport.setViewHeader(SysCommUtil.String2Clob(element.html()))
    }

    /**
     * 获取form元素实例
     * @param classFlag
     * @param id
     */
    def getWidgetParamByClassFlagAndId(classFlag,id){
        def instance
        switch (classFlag){
            case "xd-input":
                instance = XdWidgetInput.get(Long.parseLong(String.valueOf(id)))
                break;
            case "xd-select":
                instance = XdWidgetSelect.get(Long.parseLong(String.valueOf(id)))
                break;
            case "xd-date":
                instance = XdWidgetDate.get(Long.parseLong(String.valueOf(id)))
                break;
        }
        return  instance
    }

    /**
     * 保存并发布RPT
     * @param rptId
     */
    def saveRptTemp2Act(rptId){
        def deletePanelStr = SysAuthSQL.deleteRptPanelActById(rptId)
        def insertPanelStr = SysAuthSQL.insertRptPanelActById(rptId)

        def deleteParamStr = SysAuthSQL.deleteRptParamActById(rptId)
        def insertParamStr = SysAuthSQL.insertRptParamActById(rptId)

        def db = sysDBUtilService.getGroovySqlInstance()
        db.withTransaction {
            db.execute(deletePanelStr)
            //db.execute(insertPanelStr)

            db.execute(deleteParamStr)
            //db.execute(insertParamStr)
        }
        //xd_widget_report_panel,xd_widget_report_param
        def panels =  XdWidgetReportPanel.findAllByRptId(rptId)
        def params = XdWidgetReportParam.findAllByRptId(rptId)
        panels.each {
            new XdWidgetReportPanelAct(panelId: it.panelId,rptId: it.rptId,orderNum: it.orderNum).save(flush: true)
        }
        params.each {
            new XdWidgetReportParamAct(rptId:it.rptId,paramId: it.paramId,classFlag: it.classFlag,orderNum: it.orderNum).save(flush: true)
        }

        XdWidgetReport xdWidgetReport = XdWidgetReport.get(Long.parseLong(String.valueOf(rptId)))
        xdWidgetReport.setPageHeader(xdWidgetReport.viewHeader)
        xdWidgetReport.setPageBody(xdWidgetReport.viewBody)
        xdWidgetReport.save(flush: true)
    }
}
